import { defineStore } from 'pinia'
import { api } from '@/utils/api'

export const useFormStore = defineStore('form', {
  state: () => ({
    forms: [],
    pagination: null,
    currentForm: null,
    loading: false
  }),

  getters: {
    getCurrentForm: (state) => state.currentForm,
    getCurrentFormFields: (state) => state.currentForm?.config?.fields || [],
    getForms: (state) => state.forms,
    getPagination: (state) => state.pagination,
  },

  actions: {
    // 获取所有表单列表
    async getAllForms(params = {}) {
      this.loading = true
      try {
        const response = await api.forms.listAll(params)
        this.forms = response.data || []
        this.pagination = response.pagination || null
        return {
          data: this.forms,
          pagination: this.pagination
        }
      } catch (error) {
        console.error('获取所有表单失败:', error)
        // 如果API失败，返回默认数据作为fallback
        if (this.forms.length === 0) {
          this.forms = this.getDefaultFormsData()
        }
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取章节下的表单列表
    async fetchForms(sectionId) {
      this.loading = true
      try {
        const response = await api.forms.list(sectionId)
        this.forms = response.data || []
        return this.forms
      } catch (error) {
        console.error('获取表单列表失败:', error)
        // 如果API失败，返回默认数据作为fallback
        if (this.forms.length === 0) {
          this.forms = this.getDefaultFormsData()
        }
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取表单详情
    async fetchForm(formId) {
      try {
        const response = await api.forms.getById(formId)
        return response.data
      } catch (error) {
        console.error('获取表单详情失败:', error)
        throw error
      }
    },

    // 创建独立表单（不关联章节）
    async createForm(formData) {
      this.loading = true
      try {
        const response = await api.forms.create(formData)
        const newForm = response.data
        this.forms.push(newForm)
        return newForm
      } catch (error) {
        console.error('创建表单失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 在章节下创建表单
    async createFormInSection(sectionId, formData) {
      this.loading = true
      try {
        const response = await api.forms.createInSection(sectionId, formData)
        const newForm = response.data
        this.forms.push(newForm)
        return newForm
      } catch (error) {
        console.error('创建表单失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 更新表单基本信息
    async updateForm(formData) {
      this.loading = true
      try {
        const formId = formData.id || formData._id
        
        // 只发送允许更新的字段
        const updateData = {
          name: formData.name,
          order: formData.order,
          type: formData.type
        }
        
        // 移除 undefined 字段
        Object.keys(updateData).forEach(key => {
          if (updateData[key] === undefined) {
            delete updateData[key]
          }
        })
        
        const response = await api.forms.update(formId, updateData)
        const updatedForm = response.data
        
        const index = this.forms.findIndex(f => (f.id || f._id) === formId)
        if (index !== -1) {
          this.forms[index] = updatedForm
        }
        
        return updatedForm
      } catch (error) {
        console.error('更新表单失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 更新表单配置
    async updateFormConfig(formId, configData) {
      this.loading = true
      try {
        // 确保所有字段ID都是字符串
        if (configData.fields) {
          configData.fields = configData.fields.map(field => {
            const cleanField = {
              ...field,
              id: String(field.id || `field_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`)
            }
            

            
            // 处理表格字段的ID
            if (cleanField.type === 'criteriaTable') {
              if (cleanField.value?.columns) {
                cleanField.value.columns = cleanField.value.columns.map(col => ({
                  ...col,
                  id: String(col.id)
                }))
              }
              if (cleanField.value?.rows) {
                cleanField.value.rows = cleanField.value.rows.map(row => ({
                  ...row,
                  id: String(row.id || `row_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`)
                }))
              }
            }
            
            return cleanField
          })
        }
        
        const response = await api.forms.updateConfig(formId, configData)
        const updatedForm = response.data
        
        const index = this.forms.findIndex(f => (f.id || f._id) === formId)
        if (index !== -1) {
          this.forms[index] = updatedForm
        }
        
        if (this.currentForm && (this.currentForm.id || this.currentForm._id) === formId) {
          this.currentForm = updatedForm
        }
        
        return updatedForm
      } catch (error) {
        console.error('更新表单配置失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 删除表单
    async deleteForm(formId) {
      this.loading = true
      try {
        await api.forms.delete(formId)
        
        const index = this.forms.findIndex(f => (f.id || f._id) === formId)
        if (index !== -1) {
          this.forms.splice(index, 1)
        }
        
        if (this.currentForm && (this.currentForm.id || this.currentForm._id) === formId) {
          this.currentForm = null
        }
        
        return true
      } catch (error) {
        console.error('删除表单失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 复制表单
    async copyForm(formId, copyData) {
      this.loading = true
      try {
        const response = await api.forms.copy(formId, copyData)
        const newForm = response.data
        this.forms.push(newForm)
        return newForm
      } catch (error) {
        console.error('复制表单失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 添加字段
    async addField(formId, fieldData) {
      this.loading = true
      try {
        const response = await api.forms.fields.add(formId, fieldData)
        const updatedForm = response.data
        
        const index = this.forms.findIndex(f => (f.id || f._id) === formId)
        if (index !== -1) {
          this.forms[index] = updatedForm
        }
        
        if (this.currentForm && (this.currentForm.id || this.currentForm._id) === formId) {
          this.currentForm = updatedForm
        }
        
        return updatedForm
      } catch (error) {
        console.error('添加字段失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 更新字段
    async updateField(formId, fieldId, fieldData) {
      this.loading = true
      try {
        const response = await api.forms.fields.update(formId, fieldId, fieldData)
        const updatedForm = response.data
        
        const index = this.forms.findIndex(f => (f.id || f._id) === formId)
        if (index !== -1) {
          this.forms[index] = updatedForm
        }
        
        if (this.currentForm && (this.currentForm.id || this.currentForm._id) === formId) {
          this.currentForm = updatedForm
        }
        
        return updatedForm
      } catch (error) {
        console.error('更新字段失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 删除字段
    async removeField(formId, fieldId) {
      this.loading = true
      try {
        const response = await api.forms.fields.delete(formId, fieldId)
        const updatedForm = response.data
        
        const index = this.forms.findIndex(f => (f.id || f._id) === formId)
        if (index !== -1) {
          this.forms[index] = updatedForm
        }
        
        if (this.currentForm && (this.currentForm.id || this.currentForm._id) === formId) {
          this.currentForm = updatedForm
        }
        
        return updatedForm
      } catch (error) {
        console.error('删除字段失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },

    // 本地操作方法
    setCurrentForm(form) {
      this.currentForm = form
    },

    // 本地更新字段值（用于实时预览）
    updateFieldValue(fieldId, value) {
      if (!this.currentForm?.config?.fields) return

      const field = this.currentForm.config.fields.find(f => f.id === fieldId)
      if (field) {
        field.value = { ...field.value, ...value }
      }
    },

    // 本地添加字段（用于UI操作，需要后续调用API保存）
    addFieldLocal(field) {
      if (!this.currentForm?.config?.fields) {
        if (!this.currentForm.config) {
          this.currentForm.config = {}
        }
        this.currentForm.config.fields = []
      }
      this.currentForm.config.fields.push(field)
    },

    // 本地删除字段（用于UI操作，需要后续调用API保存）
    removeFieldLocal(fieldId) {
      if (!this.currentForm?.config?.fields) return

      const index = this.currentForm.config.fields.findIndex(f => f.id === fieldId)
      if (index !== -1) {
        this.currentForm.config.fields.splice(index, 1)
      }
    },

    // 本地更新字段顺序（用于拖拽排序）
    updateFieldOrder(fromIndex, toIndex) {
      if (!this.currentForm?.config?.fields) return

      const fields = this.currentForm.config.fields
      const [movedField] = fields.splice(fromIndex, 1)
      fields.splice(toIndex, 0, movedField)
    },

    // 获取默认表单数据（fallback用）
    getDefaultFormsData() {
      return [
        {
          id: 1,
          name: '患者基本信息表',
          code: 'BASIC_INFO',
          type: 'form',
          formType: 'basic',
          version: '1.0.0',
          status: '已发布',
          config: {
            fields: [
              {
                id: "field_1752054326468",
                type: "textareaField",
                name: "field_1",
                label: "文本域",
                value: {
                  value: "",
                  fieldName: "",
                  rows: 3,
                  alignment: "indent-0",
                  prefixSymbol: "",
                  isBold: false
                },
                required: true,
                validations: []
              }
            ],
            lastUpdated: new Date().toISOString()
          },
          createTime: new Date().toLocaleString(),
          updateTime: new Date().toLocaleString(),
          creator: 'admin1'
        }
      ]
    }
  }
}) 